//
//  RYCollectionContentView.swift
//  App_Profile
//
//  Created by 蒋晨成 on 2022/2/9.
//

import UICore
import UIKit

public final class RYCollectionContentView: View {
    public lazy var listViewHandler: RYCollectionHandler = {
        let handler = RYCollectionHandler()
        handler.dataSource = self.ryDataList
        return handler
    }()

    private let layout: UICollectionViewLayout

    private(set) lazy var listView: RYCollectionView = {
        let listView = RYCollectionView(layout: self.layout)
        listView.delegate = listViewHandler
        listView.dataSource = listViewHandler
        listView.backgroundColor = .clear
        return listView
    }()

    public var ryDataList: [[RYBaseCellModel]] {
        didSet {
            listViewHandler.dataSource = ryDataList
        }
    }

    public var alwaysBounceVertical: Bool = false {
        didSet {
            listView.alwaysBounceVertical = alwaysBounceVertical
        }
    }

    public init(frame: CGRect = .zero, layout: UICollectionViewLayout = UICollectionViewFlowLayout(), dataList: [[RYBaseCellModel]] = []) {
        self.layout = layout
        ryDataList = dataList
        super.init(frame: frame)
        setup()
    }

    @available(*, unavailable)
    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

public extension RYCollectionContentView {
    func registerCells(_ cells: [RYBaseCell.Type]) {
        listView.registerCells(cells)
    }

    func reloadData() {
        listView.reloadData()
    }

    func updateCellModel(cellModel: RYBaseCellModel) {
        guard let indexPath = cellModel.indexPath else { return }
        listView.reloadItems(at: [indexPath])
    }
}

private extension RYCollectionContentView {
    func setup() {
        listView.x.add(to: self).snp.makeConstraints {
            $0.edges.equalToSuperview()
        }
    }
}
